package com.dbh.self.mail;

import cn.hutool.core.convert.Convert;
import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.poi.excel.sax.handler.MapRowHandler;
import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.*;
import java.security.GeneralSecurityException;
import java.util.*;

public class SendMail {

    //简单邮件：纯文本内容
    //复杂邮件：文本+图片+附件

    /*
    *MimeMessage类表示整封邮件。
    *MimeBodyPart类表示邮件的一个MIME消息。
    *MimeMultipart类表示一个由多个MIME消息组合成的组合MIME消息。
    */

    //要发送邮件需要获取协议，开启POP3和SMTP服务
    public static void main(String[] args) throws Exception {
        List<Mail> mailList = new ArrayList<>();
        MapRowHandler mapRowHandler = new MapRowHandler(0, 138, 201) {
            @Override
            public void handleData(int sheetIndex, long rowIndex, Map<String, Object> data) {
                // 收件人邮箱地址
                String name = Convert.toStr(data.get("客户联系人"));
                name = name.trim();
                // 收件人姓名
                String mailAdress = Convert.toStr(data.get("邮箱"));
                String fromEmail = "sandy@sinohailin.com.cn";
                String fromPassword = "852db8Ze9";
                String toEmail = mailAdress.trim();
                String subject = "HVAC Thermostat and Valve -- Beijing HaiLin Controls";
                String content = "Dear "+name+"," +
                        "\n" +
                        "        Good day.\n" +
                        "\n" +
                        "        I am Sandy from Beijing HaiLin Controls. I know you have inquired us in the Alibaba platform. Thank you for your interests in HaiLin and our products.\n" +
                        "       We are a manufacturer specialized in HVAC thermostats, valves, damper actuators, sensors, DDC building auto-control systems, Auto lighting systems, etc. \n" +
                        "\n" +
                        "      Our main products line are as belows:\n" +
                        "1.       Thermostat: Control for fan Coil、electrical/water heating、Single/Multi-stage residential control, etc.\n" +
                        "2.       Valve:  FCU Motorized valve、modulating valve,  ball valve、butterfly valve, etc.\n" +
                        "3.       Damper Actuator（ include spring return damper actuator）\n" +
                        "4.       Sensor: control for Temperature、humidity、CO、CO2, etc.\n" +
                        "5.       DDC controller: Up to 8 UI port, 6DI, 3DO, 2AO, 2VO, 2 RS-485, 1 Ethernet BACnet/ModBus\n" +
                        "The attachment is a brochure for our main products for your review.\n" +
                        "\n" +
                        "Could you please tell us your demands in details. Then we’d like to provide you available products. And we can also provide customized products for you specific needs.Hope we can establish cooperation with you.   \n" +
                        " \n" +
                        "Additionally, we will attend the 35th international exhibition for refrigeration, air-conditioning, heating and ventilation industry in Beijing from April 8th to 10th, and our exhibition stand is W1F05. Welcome to your visit. \n" +
                        "\n" +
                        "Looking forward to your early reply.\n" +
                        " \n" +
                        "Best regards\n" +
                        "Sandy";
                String[] attachmentPaths = {"E:\\data\\self\\file\\PRODUCT CATALOG.pdf", "E:\\data\\self\\file\\Valve Product Catalogue.pdf", "E:\\data\\self\\file\\Easystat Thermostat Manual.pdf"};

                try {
                    sendMail(fromEmail, fromPassword, toEmail, subject, content, attachmentPaths);
                    System.out.println(rowIndex + " email send successful emial:"+toEmail+", name:" + name);
                } catch (Exception e) {

                    System.out.println("Failed to send email. Error: " + e.getMessage());
                }
                try {
                    Thread.sleep(1000L * 60 *2);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        };
//        String excelPath = "E:\\data\\self\\file\\副本阿里巴巴客户20240322.xlsx";
//        ExcelUtil.readBySax(excelPath, 1, mapRowHandler);
//
//        Mail mail = Mail.builder()
//                .sendAddress("sandy@sinohailin.com.cn")
//                .sendAuthCode("852db8Ze9")
//                .receiveAddress("dbh_123@outlook.com")
//                .title("test")
//                .content("邮件内筒1232")
//                .attachmentName("附件213")
//                .attachmentPath("E:\\data\\work\\file\\old\\至信链\\101114079907\\hLLTohoM.jpg")
//                .build();
//        sendMailForAuthCode(mail);

        sendMail();

    }

    public static void sendMail(String fromEmail, String fromPassword, String toEmail, String subject, String content, String[] attachmentPaths) throws Exception {
        // 配置邮件服务器属性
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.sinohailin.com.cn");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port", "587");

        // 创建Session对象
        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(fromEmail, fromPassword);
            }
        });

        // 创建邮件消息
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromEmail));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        message.setSubject(subject);

        // 创建邮件正文
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(content);

        // 创建Multipart对象，并将正文添加到其中
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(textPart);

        // 添加附件
        for (String attachmentPath : attachmentPaths) {
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.attachFile(attachmentPath);
            // 获取附件文件名，并进行编码
            String fileName = attachmentPart.getFileName();
            fileName = MimeUtility.encodeText(fileName, "UTF-8", "B");
            attachmentPart.setFileName(fileName);

            multipart.addBodyPart(attachmentPart);
        }

        // 将Multipart对象设置为邮件内容
        message.setContent(multipart);

        // 发送邮件
        Transport.send(message);
    }

    public static void sendMail() throws GeneralSecurityException {
        MailAccount mailAccount = new MailAccount();
        mailAccount.setAuth(true);
        mailAccount.setSslEnable(true);
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        mailAccount.setCustomProperty("mail.smtp.ssl.socketFactory", sf);

        Mail.create(mailAccount)
                .setTos("1138756325@qq.com")
                .setTitle("邮箱验证")
                .setContent("您的验证码是：<h3>2333</h3>")
                .setHtml(true)
                .send();
    }


}